package zhihui.mobile.ui.myself;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.zgm.utils.FileUtils;
import com.zgm.utils.PhotoUtils;
import com.zgm.utils.SharedPreferencesUtis;
import com.zgm.utils.ui.UiHeaderLayout;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import zhihui.mobile.R;
import zhihui.mobile.bean.shop.address.ShoppingAddress;
import zhihui.mobile.bean.user.UserInfo;
import zhihui.mobile.config.Config;
import zhihui.mobile.manager.user.UserManager;
import zhihui.mobile.presenter.IPresenter;
import zhihui.mobile.presenter.myself.UserSettingPresenter;
import zhihui.mobile.presenter.shop.BaseShopPresenter;
import zhihui.mobile.ui.BaseActivity;
import zhihui.mobile.ui.main.MainActivity;
import zhihui.mobile.ui.register.RetrievePasswordActivity;
import zhihui.mobile.ui.shop.address.ShopAddressManagerActivity;
import zhihui.mobile.ui.utils.SharedPreferenceUtils;

/**
 * Created by 张公铭 on 2017/9/24 0024.
 */
public class UserSettingActivity extends BaseActivity implements IUserSettingContract.IUSerSettingView
{
    private UserSettingPresenter settingPresenter = new UserSettingPresenter();

    private UiHeaderLayout header;
    private RelativeLayout rl_photo;
    private ImageView iv_photo;
    private RelativeLayout rl_name;
    private TextView tv_name;
    private RelativeLayout rl_sex;
    private TextView tv_sex;
    private TextView tv_phone;
    private RelativeLayout rl_password;
    private RelativeLayout rl_address;
    private TextView tv_logout;

    private Uri imageUri;
    private Uri cropImageUri;
    private static final int CODE_GALLERY_REQUEST = 0;
    private static final int CODE_CAMERA_REQUEST = 1;
    private static final int CODE_RESULT_REQUEST = 2;

    @Override
    public void initView()
    {
        header = (UiHeaderLayout) findViewById(R.id.header_setting);
        header.setLeftButtonOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                goBack(UserSettingActivity.class);
            }
        });
        header.setTitle("账号设置");
        header.hindRightOneButton();
        header.hindRightTwoButton();

        rl_photo = (RelativeLayout) findViewById(R.id.rl_setting_photo);
        rl_photo.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                showSelectPictureDialog();
            }
        });
        iv_photo = (ImageView) findViewById(R.id.iv_setting_photo);

        rl_name = (RelativeLayout) findViewById(R.id.rl_setting_name);
        rl_name.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                Intent intent = new Intent(UserSettingActivity.this, UpdateNameActivity.class);
                startActivity(intent);
            }
        });
        tv_name = (TextView) findViewById(R.id.tv_setting_name);

        rl_sex = (RelativeLayout) findViewById(R.id.rl_setting_sex);
        rl_sex.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                Intent intent = new Intent(UserSettingActivity.this, UpdateSexActivity.class);
                startActivity(intent);
            }
        });
        tv_sex = (TextView) findViewById(R.id.tv_setting_sex);

        tv_phone = (TextView) findViewById(R.id.tv_setting_phone);

        rl_password = (RelativeLayout) findViewById(R.id.rl_setting_password);
        rl_password.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                Intent intent = new Intent(UserSettingActivity.this, RetrievePasswordActivity.class);
                startActivity(intent);
            }
        });

        rl_address = (RelativeLayout) findViewById(R.id.rl_setting_address);
        rl_address.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                settingPresenter.getAddress(UserSettingActivity.this, UserSettingActivity.this, new BaseShopPresenter.IAddressSuccessListener()
                {
                    @Override
                    public void success(List<ShoppingAddress> list)
                    {
                        Intent intent = new Intent(UserSettingActivity.this, ShopAddressManagerActivity.class);
                        startActivity(intent);
                    }
                });
            }
        });

        tv_logout = (TextView) findViewById(R.id.tv_setting_logout);
        tv_logout.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                UserManager.getInstance().setCurUser(null);
                SharedPreferencesUtis.saveSharedPreference(UserSettingActivity.this, Config.USER_DATA_SAVE, Config.USER_DATA_SAVE, null);
                goBack(UserSettingActivity.class);
            }
        });
    }

    @Override
    protected int getLayoutResId()
    {
        return R.layout.user_setting_activity;
    }

    @Override
    protected IPresenter[] getPresenters()
    {
        return new IPresenter[]{settingPresenter};
    }

    @Override
    protected void onInitPresenter()
    {
        settingPresenter.init(this, this);
    }

    @Override
    public void initViewData(UserInfo userInfo)
    {
        if (!userInfo.getPic().equals("0"))
        {
            ImageLoader.getInstance().displayImage(Config.FILE_URL + userInfo.getPic(), iv_photo);
        }
        tv_sex.setText(UserInfo.getSex(userInfo.getSex()));
        tv_name.setText(userInfo.getName().equals("") ? " " : userInfo.getName());
        tv_phone.setText(userInfo.getTel());
    }

    @Override
    public void updatePhoto(String picid)
    {
        ImageLoader.getInstance().displayImage(Config.FILE_URL + picid, iv_photo);
    }

    public void showSelectPictureDialog()
    {
        final Dialog dialog = new Dialog(this, R.style.ActionSheetDialogStyle);
        View view = LayoutInflater.from(this).inflate(R.layout.picture_dialog, null);
        TextView tv_photo = (TextView) view.findViewById(R.id.tv_picture_dialog_photo);
        tv_photo.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                File outputImage = FileUtils.createNewFile(FileUtils.getDir() + Config.appDoir + "/" + System.currentTimeMillis() + ".jpg");
                //将File对象转换为Uri并启动照相程序
                imageUri = Uri.fromFile(outputImage);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
                {
                    imageUri = FileProvider.getUriForFile(UserSettingActivity.this, "com.zhihui.mobile", outputImage);
                }
                PhotoUtils.takePicture(UserSettingActivity.this, imageUri, CODE_CAMERA_REQUEST);
            }
        });

        TextView tv_album = (TextView) view.findViewById(R.id.tv_picture_dialog_album);
        tv_album.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                PhotoUtils.openPic(UserSettingActivity.this, CODE_GALLERY_REQUEST);
            }
        });

        TextView tv_cancel = (TextView) view.findViewById(R.id.tv_picture_dialog_cancel);
        tv_cancel.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                dialog.dismiss();
            }
        });

        //布局给Dialog
        dialog.setContentView(view);
        //获取当前Activity窗体
        Window window = dialog.getWindow();
        //设置dialog 从底部弹出
        window.setGravity(Gravity.BOTTOM);
        window.getDecorView().setPadding(0, 0, 0, 0);
        //获得窗体属性
        WindowManager.LayoutParams params = window.getAttributes();
        params.width = WindowManager.LayoutParams.MATCH_PARENT;
        params.y = 0;
        window.setAttributes(params);
        dialog.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        Log.i("xxxx", "UserSettingActivity onActivityResult code:" + resultCode);
        if (resultCode != RESULT_OK)
            return;

        switch (requestCode)
        {
            case CODE_CAMERA_REQUEST://拍照完成回调
                File outputImage = FileUtils.createNewFile(FileUtils.getDir() + Config.appDoir + "/" + System.currentTimeMillis() + ".jpg");
                cropImageUri = Uri.fromFile(outputImage);
                PhotoUtils.cropImageUri(this, imageUri, cropImageUri, 1, 1, 480, 480, CODE_RESULT_REQUEST);
                break;
            case CODE_GALLERY_REQUEST://访问相册完成回调
                File cropimage = FileUtils.createNewFile(FileUtils.getDir() + Config.appDoir + "/" + System.currentTimeMillis() + ".jpg");
                cropImageUri = Uri.fromFile(cropimage);
                Uri newUri = Uri.parse(PhotoUtils.getPath(this, data.getData()));
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
                {
                    newUri = FileProvider.getUriForFile(this, "com.zhihui.mobile", new File(newUri.getPath()));
                }

                PhotoUtils.cropImageUri(this, newUri, cropImageUri, 1, 1, 480, 480, CODE_RESULT_REQUEST);
                break;
            case CODE_RESULT_REQUEST:
                Bitmap bitmap = PhotoUtils.getBitmapFromUri(cropImageUri, this);
                if (bitmap != null)
                {
                    //TODO 上传到服务端
                    settingPresenter.uploadPhoto(bitmap);
                    iv_photo.setImageBitmap(bitmap);
                }
                break;
        }
    }
}
